import React from 'react';
import { Button } from 'antd';
const Index = () => {
  const mul = (...args: any[]) => {
    console.log('muling...');
    let res = 1;
    args.forEach((item) => {
      res *= item;
    });
    return res;
  };
  const proxyMul = (() => {
    const cache: { [key: string | number]: any } = {};
    return (...args: any[]) => {
      const key = [].join.call(args, ',');
      if (key in cache) {
        return cache[key];
      }
      return (cache[key] = mul.apply(null, args));
    };
  })();

// -------使用ES6 Proxy 类------------------------------------------------
  const mult = (args: any[]) => {
    console.log('muling...');
    let res = 1;
    args.forEach((item) => {
      res *= item;
    });
    return res;
  };
  const handler: { cache: { [key: string | number]: any }; apply: any } = {
    cache: {},
    apply: function (target: any, thisArg: any, args: any) {
      const key: string = [].join.call(args, ',');
      if (key in this.cache) {
        return this.cache[key];
      }
      return (this.cache[key] = target(args));
    },
  };
  // 使用ES6 Proxy 类
  // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy
  const proxyMulES6 = new Proxy(mult, handler);

  const handleClick = () => {
    console.log(mul(2, 3), 'mul');
    console.log('-------');
    console.log(proxyMul(2, 3), 'proxyMul');
    console.log('--------');
    // @ts-ignore
    console.log(proxyMulES6(2, 3), 'proxyMulES6');
    console.log('################');

  };

  return (
    <div>
      <h3>缓存代理</h3>
      <p>
        缓存代理可以为一些开销大的运算结果提供暂时的缓存，在下次运算时，如果传递进来的参数跟之前一致，则可以直接返回缓存好的运算结果。
      </p>
      <Button style={{ margin: '20px 0' }} onClick={handleClick}>
        计算2*3
      </Button>
    </div>
  );
};
export default Index;
